<script setup lang="ts">
import {
  fetchUserInfo,
  login,
} from '@/content/services/common/index'
import useAuthStore from '@/content/stores/auth'
import { ElMessage } from 'element-plus'
import {
  reactive,
  ref,
  toValue,
} from 'vue'

const state = reactive({
  loginBtnLoading: false,
  form: {
    username: '',
    password: '',
  },
  rules: {
    username: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'change',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'change',
      },
    ],
  },
})

const formRef = ref()

const visible = defineModel('visible', { default: false })

const authStore = useAuthStore()

function onLogin() {
  toValue(formRef).validate(async (valid: boolean) => {
    if (!valid)
      return

    try {
      state.loginBtnLoading = true

      const params = {
        ...state.form,
        flow: 'ever',
      }
      const { token } = await login(params)
      authStore.setToken(token)
      visible.value = false

      const { ever: { name } } = await fetchUserInfo()
      authStore.setUsername(name)

      ElMessage.success('登录成功！')
    }
    catch (error) {
      console.log('error>>>>>>', error)
    }
    finally {
      state.loginBtnLoading = false
    }
  })
}

</script>

<template>
  <ElDialog
    v-model="visible"
    title="欢迎使用LB插件,请用【羽毛】账号登录"
    width="650"
  >
    <ElForm
      ref="formRef"
      label-width="auto"
      :model="state.form"
      :rules="state.rules"
    >
      <ElFormItem
        class="mt-12px mb-24px"
        label="用户名"
        prop="username"
      >
        <ElInput
          v-model="state.form.username"
          clearable
          placeholder="请输入用户名"
        />
      </ElFormItem>

      <ElFormItem
        class="mt-12px mb-24px"
        label="密码"
        prop="password"
      >
        <ElInput
          v-model="state.form.password"
          clearable
          type="password"
          show-password
          placeholder="请输入密码"
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton
        class="w-full"
        type="primary"
        :loading="state.loginBtnLoading"
        @click="onLogin()"
      >
        登录
      </ElButton>
    </template>
  </ElDialog>
</template>
